package com.yyaccp.hncc.social.service.impl;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.service.ISysUserService;
import com.yyaccp.hncc.social.domain.SysSocialPlatform;
import com.yyaccp.hncc.social.domain.SysSocialUser;
import com.yyaccp.hncc.social.mapper.SysSocialPlatformMapper;
import com.yyaccp.hncc.social.mapper.SysSocialUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Optional;
import java.util.UUID;

import static com.yyaccp.hncc.common.SocailContants.SOCIAL_ROLE_KEY;

/**
 * @author 天天向上 （john.yi@qq.com）
 * @date 2020/8/20
 */
@Service
@RequiredArgsConstructor
public class SocialUserLoginService {
    private final SysLoginService sysLoginService;
    private final ISysUserService sysUserService;
    private final SysRoleMapper sysRoleMapper;
    private final SysSocialUserMapper sysSocialUserMapper;
    private final SysSocialPlatformMapper sysSocialPlatformMapper;
    private final BCryptPasswordEncoder passwordEncoder;
    /**
     * 1.根据platformName和socialId查询sysUserId是否为空，
     * 是，创建新用户，设置默认角色为social，设置sysUserId，并生成唯一的随机用户名，默认密码为随机用户名+salt，昵称为socialName
     * 否，取出sysUserId和用户名
     * 2.使用用户名和密码自动登录，创建token
     * @param userInfo 第三方平台返回的用户信息map
     * @param platformName
     * @return token
     */
    @Transactional(rollbackFor = Exception.class)
    public String socialLogin(Map<String, Object> userInfo, String platformName) {
        SysUser sysUser = null;
        // 找到对应社交平台的盐值
        final SysSocialPlatform platform = this.sysSocialPlatformMapper.selectSysSocialPlatformById(platformName);
        final String salt = platform.getSalt();
        // 根据条件查询社交用户
        final SysSocialUser example = new SysSocialUser();
        example.setPlatformName(platformName);
        example.setSocialId(userInfo.get("id")==null ? null : new Long(userInfo.get("id").toString()));
        example.setOpenid((String)userInfo.get("openid"));
        example.setUnionid((String)userInfo.get("unionid"));
        SysSocialUser sysSocialUser = sysSocialUserMapper.selectSysSocialUser(example);
        // 社交用户不存在（第一次登陆本系统），添加社交用户和系统用户
        if (sysSocialUser == null) {
            // 设置系统用户基本属性
            sysUser = new SysUser();
            String userName = UUID.randomUUID().toString();
            String rawPassword = userName + salt;
            sysUser.setUserName(userName);
            sysUser.setNickName((String) userInfo.get("name"));
            sysUser.setPassword(passwordEncoder.encode(rawPassword));
            // 设置系统用户默认的角色
            SysRole socialRole = sysRoleMapper.checkRoleKeyUnique(SOCIAL_ROLE_KEY);
            sysUser.setRoleIds(new Long[] {socialRole.getRoleId()});
            // 添加系统用户
            sysUserService.insertUser(sysUser);
            // 添加社交用户
            sysSocialUser = new SysSocialUser();
            sysSocialUser.setPlatformName(platformName);
            sysSocialUser.setSocialId(example.getSocialId());
            sysSocialUser.setSysUserId(sysUser.getUserId());
            sysSocialUser.setAvatarUrl((String) userInfo.get("avatar_url"));
            sysSocialUser.setSocialLoginName((String) userInfo.get("login"));
            sysSocialUser.setSocialName((String) userInfo.get("name"));
            sysSocialUserMapper.insertSysSocialUser(sysSocialUser);
        } else {
            // 通过社交用户找到系统用户
            sysUser = this.sysUserService.selectUserById(sysSocialUser.getSysUserId());
        }
        // 调用系统已有登录逻辑
        return this.sysLoginService.createToken(sysUser.getUserName(), sysUser.getUserName() + salt);
    }
}
